#include "mytask.h"

MyTask::MyTask(int hours, int minutes, int seconds, QString const &command, bool loop, bool sooi, bool ct)
    : QTreeWidgetItem({timestamp(hours, minutes, seconds), timestamp(hours, minutes, seconds), tr("Stop"), command})
    , _hours(hours)
    , _minutes(minutes)
    , _seconds(seconds)
    , _command(command)
    , _loop(loop)
    , _start_only_one_instance(sooi)
    , _consecutive_task(ct)
    , _counter(duration(hours, minutes, seconds))
    , _timer(new QTimer(this))
{

    QFont ifont; ifont.setItalic(true);
    setFont(STATE, ifont);

    _timer->setInterval(1000);  // 1s
    connect(_timer, &QTimer::timeout, this, &MyTask::execute);
}

void MyTask::execute() {
    --_counter;
    emit counter_changed(_counter, this);
    if (_counter <= 0) {

        if (!_start_only_one_instance || _pproses.empty()) {
            qDebug() << "carry on..." << _command;
            auto args = QProcess::splitCommand(_command);
            if (!args.empty()) {
                auto prog = args.takeFirst();
                auto process = new QProcess(this);
                connect(process, &QProcess::finished, this, &MyTask::process_exit);
                process->start(prog, args);
                if (process->state() == QProcess::NotRunning) {
                    qDebug() << "[NotRunning]" << _command;
                    delete process;
                }
                else {
                    _pproses.append(process);
                }
            }
        }

        stop();

        if (_loop) {
            start();
        }
    }
    setText(COUNTER, timestamp(_counter));
}

void MyTask::process_exit(int, QProcess::ExitStatus exitStatus) {
    auto proc = static_cast<QProcess*>(sender());
    const int i = _pproses.indexOf(proc);
    if (i != -1) {
        qDebug() << "delete this process...";
        delete _pproses.takeAt(i);
    }

    qDebug() << QString("[exitStatus: %1] ").arg(exitStatus) << _command;
    if (exitStatus == 0) emit finished(this);
}

void MyTask::start() {
    setForeground(STATE, Qt::darkGreen);
    setText(STATE, tr("Running"));
    if (!_timer->isActive()) _timer->start();
}

void MyTask::pause() {
    setForeground(STATE, Qt::darkRed);
    setText(STATE, tr("Paused"));
    if (_timer->isActive()) _timer->stop();
}

void MyTask::stop() {
    pause();
    setForeground(STATE, Qt::black);
    setText(STATE, tr("Stop"));
    _counter = duration(_hours, _minutes, _seconds);
    emit counter_changed(_counter, this);
    setText(COUNTER, timestamp(_counter));
}
